package com.ojoin.ojoin.eb_spider.service.impl;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ojoin.ojoin.eb_spider.check.Dispatcher;
import com.ojoin.ojoin.eb_spider.domain.AlipayAccount;
import com.ojoin.ojoin.eb_spider.domain.AlipayCheckException;
import com.ojoin.ojoin.eb_spider.domain.EmailMessage;
import com.ojoin.ojoin.eb_spider.service.AlipayAccountService;
import com.ojoin.ojoin.eb_spider.service.AlipayCheckExceptionService;
import com.ojoin.ojoin.eb_spider.service.EmailMessageService;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.EmailSendUtil;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.MoneyUtil;

@Service
public class EmailMessageServiceImpl implements EmailMessageService {

	private Logger log = LoggerFactory.getLogger(EmailMessageServiceImpl.class);

	@Autowired
	private AlipayCheckExceptionService alipayCheckExceptionService;

	@Autowired
	private AlipayAccountService alipayAccountService;

	public static final String cacheKey = "AlipayCheckException";

	@Override
	public String getHtmlReport(EmailMessage emailMessage, boolean sys) {

		List<AlipayAccount> lists = emailMessage.getAlipayAccounts();

		StringBuffer sb = new StringBuffer();


		return sb.toString();
	}

	@Override
	public String getHtmlReport(EmailMessage emailMessage) {

		return getHtmlReport(emailMessage, false);
	}

	@Override
	public boolean sendMail(EmailMessage emailMessage) {

		String address = StringUtils.join(emailMessage.getMailsAdress(), ";");

		alipayAccountService
				.initSendMailStyle(emailMessage.getAlipayAccounts());

		String html = getHtmlMonitoring(emailMessage);

		return EmailSendUtil.send(address, "报告:恒通万家", html);

	}

	@Override
	public boolean sendMailMonitoring(EmailMessage emailMessage) {

		boolean needsend = alipayAccountService.needSend(emailMessage
				.getAlipayAccounts());

		boolean issend = isSend(emailMessage);

		boolean flag = true;

		if (needsend && !issend) {

			save(emailMessage);
			
			String html = getHtmlMonitoring(emailMessage);

			flag = EmailSendUtil.send(
					StringUtils.join(emailMessage.getMailsAdress(), ";"),
					"监控:恒通万家后台", html);

			if (hasException(emailMessage)) {
				throw new BusinessException(getException(emailMessage));
			}

		} else {
			LogUtils.info(log, "发送条件为[ne edsend:%s-----issend : %s ]",
					needsend, issend);
		}

		

		return flag;
	}

	@Override
	public void save(EmailMessage emailMessage) {
		
		EmailMessage cache = Dispatcher.emailMessage.get(emailMessage.getAlipayAccountMain()
				.getUsername());
		
		if(CommonUtils.isEmpty(cache)){
			Dispatcher.emailMessage.put(emailMessage.getAlipayAccountMain()
					.getUsername(), emailMessage);
			
			return ;
		}
		
		Map<String, AlipayCheckException> map = alipayCheckExceptionService
				.getCache(cache);

		// 保存提现记录
		List<AlipayAccount> list = emailMessage.getAlipayAccounts();

		Iterator<AlipayAccount> itall = list.iterator();

		while (itall.hasNext()) {
			AlipayAccount ap = itall.next();
			AlipayCheckException aps = map.get(ap
					.getUsername());
			List<String> li = ap.getAlipayCheckException().getWithdrawDeposit();

			if (!CommonUtils.isEmpty(li)) {
				Iterator<String> it = li.iterator();
				while (it.hasNext()) {
					String with = it.next();
					if (!aps.getWithdrawDeposit().contains(with)) {
						aps.getWithdrawDeposit().add(with);
					}
				}
			}

			/**
			 * 绑定银行卡
			 */
			List<String> BoundCards = ap.getAlipayCheckException()
					.getBoundCard();

			if (!CommonUtils.isEmpty(BoundCards)) {
				Iterator<String> it = BoundCards.iterator();
				while (it.hasNext()) {
					String with = it.next();
					if (!aps.getBoundCard().contains(with)) {
						aps.getBoundCard().add(with);
					}
				}
			}

			/**
			 * 关联
			 */
			Set<String> relations = ap.getAlipayCheckException().getRelations();

			if (!CommonUtils.isEmpty(relations)) {
				Iterator<String> it = relations.iterator();
				while (it.hasNext()) {
					String with = it.next();
					if (!aps.getRelations().contains(with)) {
						aps.getRelations().add(with);
					}
				}
			}
			
			Map<String, Exception> exception = ap.getAlipayCheckException().getException();
			
			if (!CommonUtils.isEmpty(exception)) {
				Set<Map.Entry<String, Exception>> set = exception.entrySet();
				Iterator<Map.Entry<String, Exception>> it = set.iterator();
				
				while (it.hasNext()) {
					Map.Entry<String, Exception> with = it.next();
					
					if(CommonUtils.isEmpty(aps.getException().get(with.getKey()))){
						aps.getException().put(with.getKey(), with.getValue());
					}
				}
			}
			
			aps.setAmountInArrear(ap.getAlipayCheckException().getAmountInArrear());
			aps.setTmallUnpaySettleorder(ap.getAlipayCheckException().getTmallUnpaySettleorder());
		}

	}

	@Override
	public void remove() {
		Dispatcher.emailMessage.clear();

	}

	@Override
	public EmailMessage getCache(String username) {
		return Dispatcher.emailMessage.get(username);
	}

	@Override
	public boolean isSend(EmailMessage emailMessage) {
		EmailMessage cache = getCache(emailMessage.getAlipayAccountMain()
				.getUsername());
		Map<String, AlipayCheckException> map = alipayCheckExceptionService
				.getCache(cache);

		return alipayCheckExceptionService.isSend(map,
				emailMessage.getAlipayAccounts());
	}

	@Override
	public boolean sendMailMonitoring(String username) {
		EmailMessage cache = getCache(username);

		if (!CommonUtils.isEmpty(cache)) {
			String address = StringUtils.join(cache.getMailsAdress(), ";");

			String html = getHtmlMonitoring(cache);

			return EmailSendUtil.send(address, "监控:恒通万家后台未处理异常", html);
		} else {
			LogUtils.info(log, "cache中邮件为空");
			return true;
		}

	}

	@Override
	public String getHtmlMonitoring(EmailMessage emailMessage) {

		List<AlipayAccount> lists = emailMessage.getAlipayAccounts();

		StringBuffer html = new StringBuffer();
		html.append("<html><body><table border=\"1\" cellpadding=\"2\" cellspacing=\"0\">");
		StringBuffer shopName = new StringBuffer("<tr><td>店铺名称</td>");
		StringBuffer shopType = new StringBuffer("<tr><td>账号类别</td>");
		StringBuffer name = new StringBuffer("<tr><td>账号名称</td>");
		StringBuffer login = new StringBuffer("<tr><td>登陆状态</td>");
		StringBuffer balancePay = new StringBuffer("<tr><td>余额支付</td>");
		StringBuffer wirelessPay = new StringBuffer("<tr><td>无线支付</td>");
		StringBuffer relations = new StringBuffer("<tr><td>关联账号</td>");
		StringBuffer boundCard = new StringBuffer("<tr><td>银行账户</td>");
		StringBuffer withdrawDeposit = new StringBuffer("<tr><td>提现记录</td>");
		StringBuffer Balance = new StringBuffer("<tr><td>可用+冻结</td>");
		StringBuffer availableBalance = new StringBuffer("<tr><td>支付宝可用余额</td>");
		StringBuffer disableBalance = new StringBuffer("<tr><td>支付宝余额冻结余额</td>");
		StringBuffer caiNaioInventory = new StringBuffer("<tr><td>菜鸟货物价值折算金额</td>");
		
		StringBuffer paymoney = new StringBuffer("<tr><td>天猫应收帐款可提金额</td>");
		
		StringBuffer amountInArrear = new StringBuffer("<tr><td>负债总金额</td>");
		StringBuffer tdcell = new StringBuffer("<tr><td>可贷金额</td>");

		if (!CommonUtils.isEmpty(lists)) {
			Iterator<AlipayAccount> it = lists.iterator();
			while (it.hasNext()) {
				AlipayAccount aa = it.next();
				
				EmailMessage cache = getCache(emailMessage.getAlipayAccountMain()
						.getUsername());
				
				Map<String, AlipayCheckException> map = alipayCheckExceptionService
						.getCache(cache);
				AlipayCheckException stand = Dispatcher.stands.get(emailMessage.getAlipayAccountMain()
						.getUsername());
				
				AlipayCheckException acs ;
				
				if(CommonUtils.isEmpty(map)){
					acs = new AlipayCheckException();
				}else {
					acs = map.get(aa
							.getUsername());
				}
				
				
				
				AlipayCheckException ac = aa.getAlipayCheckException();
				shopName.append("<td>" + aa.getNameOfShop() + "</td>");
				shopType.append("<td>" + aa.getStatuesName() + "</td>");
				name.append("<td>" + aa.getUsername() + "</td>");

				if (CommonUtils.isEmpty(ac.getLogIn())) {
					login.append(alipayCheckExceptionService.getHtmlStyle(
							"red", "抓取异常"));
				} else if (ac.getLogIn().equals("失败")) {
					login.append(alipayCheckExceptionService.getHtmlStyle(
							"red", ac.getLogIn()));
				} else {
					login.append(alipayCheckExceptionService.getHtmlStyle(ac
							.getLogIn()));
				}

				if (CommonUtils.isEmpty(ac.getBalancePay())) {
					balancePay.append(alipayCheckExceptionService.getHtmlStyle(
							"red", "抓取异常"));

				} else if (ac.getBalancePay().equals("开")) {
					balancePay.append(alipayCheckExceptionService.getHtmlStyle(
							"red", ac.getBalancePay()));

				} else {
					balancePay.append(alipayCheckExceptionService
							.getHtmlStyle(ac.getBalancePay()));
				}

				wirelessPay.append("<td>" + ac.getWirelessPay() + "</td>");

				relations.append("<td>");
				Set<String> relation = ac.getRelations();
				if (!CommonUtils.isEmpty(relation)) {
					Iterator<String> its = relation.iterator();
					while (its.hasNext()) {
						String ss = its.next();
						if (!CommonUtils.isEmpty(acs)) {
							if (acs.getRelations().contains(ss)) {
								relations.append((alipayCheckExceptionService
										.getHtmlFontStyle(ss)));
							} else {
								relations.append((alipayCheckExceptionService
										.getHtmlFontStyle("red", ss)));
							}
						} else {
							relations.append((alipayCheckExceptionService
									.getHtmlFontStyle("red", ss)));
						}

					}
				} else {
					relations.append((alipayCheckExceptionService
							.getHtmlFontStyle("red", "抓取异常")));
				}
				relations.append("</td>");

				boundCard.append("<td>");
				List<String> bound = ac.getBoundCard();
				if (!CommonUtils.isEmpty(bound)) {
					Iterator<String> its = bound.iterator();
					while (its.hasNext()) {
						String ss = its.next();
						if (!CommonUtils.isEmpty(acs)) {
							if (acs.getBoundCard().contains(ss)) {
								boundCard.append((alipayCheckExceptionService
										.getHtmlFontStyle(ss)));
							} else {
								boundCard.append((alipayCheckExceptionService
										.getHtmlFontStyle("red", ss)));
							}
						} else {
							boundCard.append((alipayCheckExceptionService
									.getHtmlFontStyle("red", ss)));
						}

					}
				} else {
					boundCard.append((alipayCheckExceptionService
							.getHtmlFontStyle("red", "抓取异常")));
				}
				boundCard.append("</td>");

				withdrawDeposit.append("<td>");
				List<String> with = ac.getWithdrawDeposit();
				if (!CommonUtils.isEmpty(with)) {
					Iterator<String> its = with.iterator();
					while (its.hasNext()) {
						String ss = its.next();
						if (!CommonUtils.isEmpty(acs)) {
							if (acs.getWithdrawDeposit().contains(ss)) {
								withdrawDeposit
										.append((alipayCheckExceptionService
												.getHtmlFontStyle(ss)));
							} else {
								withdrawDeposit
										.append((alipayCheckExceptionService
												.getHtmlFontStyle("red", ss)));
							}
						} else {
							withdrawDeposit.append((alipayCheckExceptionService
									.getHtmlFontStyle(ss)));
						}
					}
				} else {
					withdrawDeposit.append((alipayCheckExceptionService
							.getHtmlFontStyle("red", "抓取异常")));
				}
				withdrawDeposit.append("</td>");

				Balance.append("<td>"
						+ (CommonUtils.isEmpty(ac.getAvailableBalance()) && CommonUtils.isEmpty(ac.getDisableBalance()) ? ""
								: "当前总额"
										+ MoneyUtil.getDisplayRMB(String.valueOf(ac
												.getAvailableBalance()
												+ ac.getDisableBalance())))
						+ "</br>"
						+ (CommonUtils.isEmpty(stand
								.getAvailableBalanceStartingValue()) ? ""
								: "初始总额"
										+ MoneyUtil.getDisplayRMB(String.valueOf(stand
												.getAvailableBalanceStartingValue()
												+ stand.getDisableBalanceStartingValue())))
						+ "</td>");
				availableBalance
						.append("<td>"
								+ (CommonUtils.isEmpty(ac.getAvailableBalance()) ? ""
										: "当前总额"
												+ MoneyUtil.getDisplayRMB(String.valueOf(ac
														.getAvailableBalance())))
								+ ""
								+ "</br>"
								+ (CommonUtils.isEmpty(stand
										.getAvailableBalanceStartingValue()) ? ""
										: "初始总额"
												+ MoneyUtil.getDisplayRMB(String.valueOf(stand
														.getAvailableBalanceStartingValue())))
								+ "</td>");
				disableBalance
						.append("<td>"
								+ (CommonUtils.isEmpty(ac.getDisableBalance()) ? ""
										: "当前总额"
												+ MoneyUtil.getDisplayRMB(String.valueOf(ac
														.getDisableBalance())))
								+ ""
								+ "</br>"
								+ (CommonUtils.isEmpty(stand
										.getDisableBalanceStartingValue()) ? ""
										: "初始总额"
												+ MoneyUtil.getDisplayRMB(String.valueOf(stand
														.getDisableBalanceStartingValue())))
								+ "</td>");

				caiNaioInventory.append("<td>"
						+ (CommonUtils.isEmpty(ac.getCaiNiaoSettleorder()) ? ""
								: ac.getCaiNiaoSettleorderDetail()+"</br>当前总额["
										+MoneyUtil.getDisplayRMB(String
												.valueOf(ac.getCaiNiaoSettleorder()))+"]")
						+ "</td>");

				paymoney.append("<td>"
						+ (CommonUtils.isEmpty(ac.getTmallUnpaySettleorder()) ? ""
								:ac.getTmallUnpaySettleorderDetail()+ "</br>当前总额["
										+MoneyUtil.getDisplayRMB(String
												.valueOf(ac.getTmallUnpaySettleorder()))+"]")
						+ "</td>");
				
				String aia = "";
				if(CommonUtils.isEqual(ac.getAmountInArrear(), acs.getAmountInArrear())){
					if(!CommonUtils.isEmpty(ac.getAmountInArrear())){
						aia = MoneyUtil.getDisplayRMB(String.valueOf(ac
								.getAmountInArrear()));
					}
				}else {
					if(!CommonUtils.isEmpty(ac.getAmountInArrear())){
						aia = MoneyUtil.getDisplayRMB(String.valueOf(ac
								.getAmountInArrear()));
						
						aia = alipayCheckExceptionService
								.getHtmlFontStyle("red",aia);
					}
				}
				
				amountInArrear.append("<td>"
						+ aia + "</td>");

				String cell = "";
				try {
					cell = MoneyUtil.getDisplayRMB(String
							.valueOf(alipayAccountService.getCanSell(aa)));
				} catch (Exception e) {
					cell = e.getMessage();
				}

				tdcell.append("<td>" + cell + "</td>");
			}
		}

		shopName.append("</td>");
		shopType.append("</td>");
		name.append("</td>");
		login.append("</td>");
		balancePay.append("</td>");
		wirelessPay.append("</td>");
		relations.append("</td>");
		boundCard.append("</td>");
		withdrawDeposit.append("</td>");
		Balance.append("</td>");
		availableBalance.append("</td>");
		disableBalance.append("</td>");
		caiNaioInventory.append("</td>");
		paymoney.append("</td>");
		tdcell.append("</td>");

		return html.append(shopName).append(shopType).append(name)
				.append(login).append(balancePay).append(wirelessPay)
				.append(relations).append(boundCard).append(withdrawDeposit)
				.append(Balance).append(availableBalance)
				.append(disableBalance).append(caiNaioInventory).append(paymoney)
				.append(amountInArrear).append(tdcell)
				.append("</table></body></html>").toString();
	}

	@Override
	public boolean sendMailException(EmailMessage emailMessage) {
		String address = StringUtils.join(
				emailMessage.getMailsAdressMonitoring(), ";");

		String content = "";

		if (emailMessage.getException() instanceof BusinessException) {
			content = emailMessage.getException().getMessage();
		} else {
			content = ExceptionUtils.getRootCauseMessage(emailMessage
					.getException());
		}

		return EmailSendUtil.send(address, "恒通万家监控系统异常", content);
	}

	@Override
	public boolean hasException(EmailMessage emailMessage) {
		if (!CommonUtils.isEmpty(emailMessage)) {
			if (!CommonUtils.isEmpty(emailMessage.getException())) {
				return true;
			}
			

			// 天猫抓取是否出现异常
			List<AlipayAccount> li = emailMessage.getAlipayAccounts();

			if (!CommonUtils.isEmpty(li)) {
				Iterator<AlipayAccount> it = li.iterator();
				while (it.hasNext()) {
					AlipayAccount aa = it.next();
					AlipayCheckException ac = aa.getAlipayCheckException();
					if (!CommonUtils.isEmpty(ac.getException())
							&& ac.getException().size() > 0) {
						return true;
					}
				}
			}

		}
		return false;
	}

	@Override
	public String getException(EmailMessage emailMessage) {
		StringBuffer sb = new StringBuffer();
		sb.append("<html><body><table border=\"1\" cellpadding=\"2\" cellspacing=\"0\">");

		if (!CommonUtils.isEmpty(emailMessage)) {
			if (!CommonUtils.isEmpty(emailMessage.getException())) {
				sb.append("<tr><td>全局异常</td><td>"
						+ ExceptionUtils.getRootCauseMessage(emailMessage
								.getException()) + "</td></tr>");
			}

			// 天猫抓取是否出现异常
			List<AlipayAccount> li = emailMessage.getAlipayAccounts();

			if (!CommonUtils.isEmpty(li)) {
				Iterator<AlipayAccount> it = li.iterator();
				while (it.hasNext()) {
					AlipayAccount aa = it.next();
					AlipayCheckException ac = aa.getAlipayCheckException();
					if (!CommonUtils.isEmpty(ac.getException())) {

						Map<String, Exception> me = ac.getException();
						Set<Map.Entry<String, Exception>> set = me.entrySet();
						Iterator<Map.Entry<String, Exception>> itm = set
								.iterator();
						while (itm.hasNext()) {
							Map.Entry<String, Exception> mape = itm.next();
							sb.append("<tr><td>"
									+ aa.getUsername()
									+ "</td><td>"
									+ mape.getKey()
									+ "-----"
									+ ExceptionUtils.getRootCauseMessage(mape
											.getValue()) + "</td></tr>");
						}
					}
				}
			}

		}

		sb.append("</table></body></html>");

		return sb.toString();
	}

	
/*	public List<String> getAlipayCheckException(InputStream in,
			String uname) throws DocumentException {
		AlipayCheckException alipayCheckException = null ;
		SAXReader saxReader = new SAXReader();

		Document document = saxReader.read(in);
		Element employees = document.getRootElement();

		Iterator i = employees.elementIterator();

		while (i.hasNext()) {
			Element employee = (Element) i.next();

			String name = employee.element("username").getText();
			if (name.equals(uname)) {
				
				String boundCard = employee.element("boundCard").getText();
				String checkedStartTime = employee.element("checkedStartTime")
						.getText();

				String availableBalanceStartingValue = employee.element("availableBalanceStartingValue")
						.getText();
				
				String disableBalanceStartingValue = employee.element("disableBalanceStartingValue")
						.getText();
				 
				alipayCheckException = new AlipayCheckException(Long.valueOf(availableBalanceStartingValue),Long.valueOf(disableBalanceStartingValue));
				
				alipayCheckException.getBoundCard().add(boundCard);
				alipayCheckException.setCheckedStartTime(TimeUtils
						.getDate(checkedStartTime));
				
		
				
			}
		}

		return alipayCheckException;
	}*/
	
	
}
